package com.piece.blog.interceptor;

import com.piece.blog.controller.BlogManageController;
import com.piece.blog.model.Article;
import com.piece.core.framework.constant.FrameWorkConstants;
import com.piece.core.framework.enums.StatusType;
import com.piece.core.framework.util.object.BeanUtil;
import com.piece.core.framework.util.object.ClassUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.web.interceptor.InterceptorHookSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.Enumeration;

/**
 * 文章内容自动加入Copyright
 */
@Slf4j
@Component
public class ViewCopyrightPlugin extends InterceptorHookSupport {

    @Override
    public String[] getInterceptor() {
        // 说明要拦截的controller
        return new String[]{BlogManageController.class.getName()};
    }

    @Override
    public void preHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) {
        String method = handler.getMethod().getName();
        request.setAttribute("isRegister", true);

        if ("view".equals(method)) {
            Article article = new Article();
            initDB(request, article);
            // 判断文章是否为加密文章
            if (StatusType.NORMAL.getCode().equals(article.getCrypto())) {
                article.setSummary(null);
                article.setContent(null);
                request.setAttribute("requireCrypto", true);
            } else {
                request.setAttribute("requireCrypto", false);
                setCopyright(article, article.getContent());
            }
        }
    }

    /**
     * 请求内容转换成对象
     */
    public void initDB(HttpServletRequest request, Object obj) {
        //查询条件
        Enumeration<?> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            String prefixName = "";
            if (StringUtil.isNotEmpty(paraName)) {
                try {
                    Field field = BeanUtil.getFieldByFieldName(obj.getClass(), paraName);
                    if (null == field) {
                        continue;
                    }

                    // 不为非基础类赋值
                    if (!ClassUtil.isJavaClass(field.getType())) {
                        continue;
                    }

                    Object value = request.getParameter(prefixName + paraName);
                    if (paraName.indexOf("[") < 0) {
                        if (StringUtil.isEmptyParameter(value.toString())) {
                            value = null;
                        }
                        try {
                            BeanUtil.setFieldValue(obj, paraName, value);
                        } catch (Exception e) {
                        }
                    } else {
                        //传的是数组
                        String[] arr = request.getParameterValues(prefixName + paraName);
                        paraName = paraName.replace("[]", "");
                        try {
                            BeanUtil.setFieldValue(obj, paraName, StringUtil.join(arr, FrameWorkConstants.SPLIT_PARAM));
                        } catch (Exception e) {

                        }
                    }
                } catch (Exception e) {
                }
            }
        }
    }

    private void setCopyright(Article article, String content) {
        if (null != content && !"4".equals(article.getChannel()) && !content.endsWith("本文归作者所有，未经作者允许，不得转载</p>")) {
            content += "<br/><p class=\"copyright\">注意：本文归作者所有，未经作者允许，不得转载</p>";
            article.setContent(content);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, Exception ex) throws Exception {
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler) throws Exception {
    }
}
